package com.systemCapacity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.systemCapacity.common.dto.*;
import com.systemCapacity.entity.*;
import com.systemCapacity.entity.Enum.TemplateType;
import com.systemCapacity.entity.Enum.TenCapacityType;
import com.systemCapacity.mapper.BattleActivityMapper;
import com.systemCapacity.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class BattleActivityServiceImpl extends ServiceImpl<BattleActivityMapper, BattleActivity>
        implements BattleActivityService {

    @Autowired
    ActivityResourceService activityResourceService;

    @Autowired
    BattleActivityMapper battleActivityMapper;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    EquipmentTemplateService equipmentTemplateService;

    @Autowired
    BattlePlatformService battlePlatformService;

    @Autowired
    BattlePlatformDeviceService battlePlatformDeviceService;

    @Autowired
    BattleCapacityService battleCapacityService;

    @Autowired
    AttributeService attributeService;

    @Autowired
    DeviceService deviceService;

    @Override
    public List<BattleActivityDto> getActivities(String planId, boolean totalPah) {
        QueryWrapper<BattleActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planId", planId);
        queryWrapper.orderByAsc("activityNum");
        List<BattleActivity> activities = battleActivityMapper.selectList(queryWrapper);
        List<BattleActivityDto> dtos = activities.stream().map(
                battleActivity -> BeanUtil.copyProperties(battleActivity, BattleActivityDto.class)
        ).collect(Collectors.toList());
        for (BattleActivityDto dto : dtos) {
            // 设置资源参数和性能参数
            dto.setActivityResourceRequests(activityResourceService.getResourceRequests(dto.getActivityId(), totalPah));
            if (totalPah) {
                for (ActivityResourceRequestDto activityDto : dto.getActivityResourceRequests()) {
                    Equipment equipment = equipmentService.getById(activityDto.getEquipmentId());
                    StringBuilder totalName = new StringBuilder(equipmentTemplateService.getPrefixByEquipmentId(equipment));
                    activityDto.setEquipmentName(totalName.append(activityDto.getEquipmentName()).toString());
                }
            }
            dto.setSatisfied(activitySatisfied(dto));
        }
        return dtos;
    }

    @Override
    public List<BattleActivityDto> getActivitiesByPlanId(String planId) {
        QueryWrapper<BattleActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planId", planId);
        queryWrapper.orderByAsc("activityNum");
        List<BattleActivity> activities = battleActivityMapper.selectList(queryWrapper);
        List<BattleActivityDto> dtos = activities.stream().map(
                battleActivity -> BeanUtil.copyProperties(battleActivity, BattleActivityDto.class)
        ).collect(Collectors.toList());
        for (BattleActivityDto dto : dtos) {
            //查询平台
            QueryWrapper<BattlePlatform> queryPlatform = new QueryWrapper<>();
            queryPlatform.eq("activityId",dto.getActivityId());
            List<BattlePlatform> platformList = battlePlatformService.list(queryPlatform);
            List<BattlePlatformDto> platformDtoList = platformList.stream().map(x -> {
                BattlePlatformDto battlePlatformDto = new BattlePlatformDto();
                BeanUtil.copyProperties(x, battlePlatformDto);
                QueryWrapper<Equipment> queryEquipment = new QueryWrapper<>();
                queryEquipment.eq("equipmentId",x.getEquipmentId());
                Equipment equipment = equipmentService.getOne(queryEquipment);
                battlePlatformDto.setEquipmentName(equipment.getEquipmentName());
                battlePlatformDto.setEquipmentWeight(equipment.getWeight());

                //查询装备模型
                QueryWrapper<EquipmentTemplate> templateQueryWrapper = new QueryWrapper<>();
                templateQueryWrapper.eq("templateId",equipment.getPTemplateId());
                EquipmentTemplate template = equipmentTemplateService.getOne(templateQueryWrapper);
                battlePlatformDto.setTemplateName(template.getTemplateName());
                return battlePlatformDto;
            }).collect(Collectors.toList());
            dto.setPlatFormList(platformDtoList);

            //查询平台下面设备
            platformDtoList.forEach(x -> {
                QueryWrapper<BattlePlatformDevice> queryDevice = new QueryWrapper<>();
                queryDevice.eq("platformId",x.getPlatformId());
                List<BattlePlatformDevice> platformDeviceList = battlePlatformDeviceService.list(queryDevice);

                if(platformDeviceList.isEmpty()){
                    x.setPlatformDeviceList(new ArrayList<>());
                }else{
                    List<BattlePlatformDeviceDto> battlePlatformDeviceDtoList = platformDeviceList.stream().map(item -> {
                        BattlePlatformDeviceDto battlePlatformDeviceDto = new BattlePlatformDeviceDto();
                        BeanUtil.copyProperties(item, battlePlatformDeviceDto);
                        //查询设备名称
                        QueryWrapper<Device> queryDeviceObj = new QueryWrapper<>();
                        queryDeviceObj.eq("deviceId",item.getDeviceId());
                        Device deviceObj = deviceService.getOne(queryDeviceObj);
                        battlePlatformDeviceDto.setDeviceName(deviceObj.getDeviceName());
                        battlePlatformDeviceDto.setDeviceWeight(deviceObj.getWeight());

                        //查询能力
                        QueryWrapper<BattleCapacity> capacityQueryWrapper = new QueryWrapper<>();
                        capacityQueryWrapper.eq("capacityId",item.getCapacityId());
                        BattleCapacity battleCapacity = battleCapacityService.getOne(capacityQueryWrapper);
                        if(battleCapacity != null){
                            battlePlatformDeviceDto.setCapacityName(battleCapacity.getCapacityName());
                        }
                        //查询父能力
                        capacityQueryWrapper = new QueryWrapper<>();
                        capacityQueryWrapper.eq("capacityId",battleCapacity.getPid());
                        BattleCapacity parentBattleCapacity = battleCapacityService.getOne(capacityQueryWrapper);
                        if(parentBattleCapacity != null){
                            battlePlatformDeviceDto.setParentCapacityName(parentBattleCapacity.getCapacityName());
                        }
                        //根节点能力
                        battlePlatformDeviceDto.setRootCapacityName(battleCapacity.getCapacityType().getDes());
                        battlePlatformDeviceDto.setCapacityType(battleCapacity.getCapacityType());

                        return battlePlatformDeviceDto;
                    }).collect(Collectors.toList());
                    x.setPlatformDeviceList(battlePlatformDeviceDtoList);
                }
                //查询平台具备的能力
                List<BattleCapacityDto> capacityDtoList = battleCapacityService.queryCapacityListByType(x.getTemplateName());
                x.setCapacityDtoList(capacityDtoList);
                List<BlueEquipmentDto> equipmentBlueAttributeList = attributeService.getEquipmentBlueAttributes(x.getEquipmentId());
                List<String> equipmentNameList = equipmentBlueAttributeList.stream().map(j -> j.getEquipmentName()).collect(Collectors.toList());
                x.setEquipmentNameList(equipmentNameList);
                x.setEquipmentList(equipmentBlueAttributeList);
            });
        }
        return dtos;
    }


    @Override
    @Transactional
    public boolean saveActivity(BattleActivityDto dto, String planId) {
        BattleActivity activity = new BattleActivity();
        activity.setActivityId(UUID.randomUUID().toString());
        activity.setActivityNum(dto.getActivityNum());
        activity.setPlanId(planId);
        activity.setActivityType(dto.getActivityType().getValue());
        activity.setStepDes(dto.getStepDes());
        activity.setActivityDes(dto.getActivityDes());
        save(activity);

        //保存平台
        List<BattlePlatformDto> plalatFormList = dto.getPlatFormList();
        plalatFormList.forEach(x -> {
            x.setPlanId(planId);
            x.setActivityId(activity.getActivityId());
        });
        battlePlatformService.savePlatForm(plalatFormList);
//        List<ActivityResourceRequestDto> requests = dto.getActivityResourceRequests();
//        requests.forEach(activityResourceRequestDto ->
//                activityResourceService.saveResourceRequest(activityResourceRequestDto, activity.getActivityId()));
        return true;
    }

    /**
     * 先删除作战需求，然后删除作战方案下的所有作战活动
     * @param planId 作战方案id
     * @return 操作是否成功
     */
    @Override
    @Transactional
    public boolean deleteActivityByPlanId(String planId) {
        QueryWrapper<BattleActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planId", planId);
        List<BattleActivity> activities = battleActivityMapper.selectList(queryWrapper);
        activities.forEach(battleActivity ->
                activityResourceService.deleteResourceRequestByActivityId(battleActivity.getActivityId()));
        return remove(queryWrapper);
    }

    /**
     * @param planId 作战方案id
     * @return 操作是否成功
     */
    @Override
    @Transactional
    public boolean deleteActivityByPlanIdNew(String planId) {
        QueryWrapper<BattleActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planId", planId);
        List<BattleActivity> activities = battleActivityMapper.selectList(queryWrapper);

        //删除活动下面的平台数据
        List<String> activityIdList = activities.stream().map(BattleActivity::getActivityId).collect(Collectors.toList());
        if (!activityIdList.isEmpty()) {
            battlePlatformService.deletePlatformByActivityIdList(activityIdList);
            return remove(queryWrapper);
        }
        return true;
    }

    @Override
    public void evaluateActivity(BattleActivityDto activity) {
        List<String> equipmentIds = activityResourceService.getActivityEquipment(activity.getActivityId());
        List<String> templateIds = equipmentService.getEquipmentTemplates(equipmentIds);
        List<Integer> types = equipmentTemplateService.getTemplateType(templateIds);
        StringBuilder stringBuilder = new StringBuilder();
        types.forEach(stringBuilder::append);
        String typeStr = stringBuilder.toString();
        StringBuilder satisfiedBuilder = new StringBuilder();
        switch (activity.getActivityType()) {
            case DISCOVERY:
                if (!typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue()))) {
                    satisfiedBuilder.append("发现环节必须包含数据链装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue()))) {
                    satisfiedBuilder.append("发现环节必须包含传感器装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue()))) {
                    satisfiedBuilder.append("发现环节必须包含平台装备;");
                }
                break;
            case POSITIONING:
                if (!typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue()))) {
                    satisfiedBuilder.append("定位环节必须包含数据链装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue()))) {
                    satisfiedBuilder.append("定位环节必须包含传感器装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue()))) {
                    satisfiedBuilder.append("定位环节必须包含平台装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()))) {
                    satisfiedBuilder.append("定位环节必须包含指控装备;");
                }
                break;
            case TRACKING:
                if (!typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue()))) {
                    satisfiedBuilder.append("追踪环节必须包含数据链装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue()))) {
                    satisfiedBuilder.append("追踪环节必须包含传感器装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue()))) {
                    satisfiedBuilder.append("追踪环节必须包含平台装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()))) {
                    satisfiedBuilder.append("追踪环节必须包含指控装备;");
                }
                break;
            case AIMING:
                if (!typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue()))) {
                    satisfiedBuilder.append("瞄准环节必须包含数据链装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue()))) {
                    satisfiedBuilder.append("瞄准环节必须包含传感器装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue()))) {
                    satisfiedBuilder.append("满足环节必须包含平台装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()))) {
                    satisfiedBuilder.append("瞄准环节必须包含指控装备;");
                }
                break;
            case STRIKING:
                if (!typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue()))) {
                    satisfiedBuilder.append("打击环节必须包含数据链装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue()))) {
                    satisfiedBuilder.append("打击环节必须包含传感器装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue()))) {
                    satisfiedBuilder.append("打击环节必须包含平台装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()))) {
                    satisfiedBuilder.append("打击环节必须包含指控装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.WEAPON.getValue()))) {
                    satisfiedBuilder.append("打击环节必须包含武器装备;");
                }
                break;
            case ESTIMATING:
                if (!typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue()))) {
                    satisfiedBuilder.append("评估环节必须包含数据链装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue()))) {
                    satisfiedBuilder.append("评估环节必须包含传感器装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue()))) {
                    satisfiedBuilder.append("评估环节必须包含平台装备;");
                }
                if (!typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()))) {
                    satisfiedBuilder.append("评估环节必须包含指控装备;");
                }
                break;
            default:
                break;
        }
        activity.setSatisfiedStr(satisfiedBuilder.toString());
    }

    /**
     * 查询相关作战方案
     * @param ids 作战活动id
     * @return 作战方案列表
     */
    @Override
    public List<String> getBattlePlans(List<String> ids) {
        QueryWrapper<BattleActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("activityId", ids);
        queryWrapper.groupBy("planId");
        List<Map<String, Object>> maps = listMaps(queryWrapper);
        return null;
    }

    private boolean activitySatisfied(BattleActivityDto dto) {
        List<String> equipmentIds = activityResourceService.getActivityEquipment(dto.getActivityId());
        List<String> templateIds = equipmentService.getEquipmentTemplates(equipmentIds);
        List<Integer> types = equipmentTemplateService.getTemplateType(templateIds);
        StringBuilder stringBuilder = new StringBuilder();
        types.forEach(stringBuilder::append);
        String typeStr = stringBuilder.toString();
        switch (dto.getActivityType()) {
            case DISCOVERY:
                return typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue()));
            case POSITIONING:
                return typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()));
            case TRACKING:
                return typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()));
            case AIMING:
                return typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()));
            case STRIKING:
                return typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.WEAPON.getValue()));
            case ESTIMATING:
                return typeStr.contains(String.valueOf(TemplateType.CHAIN.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.SENSOR.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.PLATFORM.getValue())) &&
                        typeStr.contains(String.valueOf(TemplateType.ALLEGATION.getValue()));
        }
        return false;
    }
}
